import { fileURLToPath, URL } from 'node:url'
import { execSync } from 'node:child_process'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { VantResolver } from '@vant/auto-import-resolver'
import postcssPx2vp from 'postcss-px2vp'
import vueattrPxtoremvw from 'vueattr-pxtoremvw/vite'

// 获取 Git 分支名称
const getGitBranch = () => {
  try {
    return execSync('git rev-parse --abbrev-ref HEAD').toString().trim()
  } catch {
    return 'unknown'
  }
}

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 根据当前工作目录中的 `mode` 加载 .env 文件
  // 设置第三个参数为 '' 来加载所有环境变量，而不管是否有 `VITE_` 前缀。
  const env = loadEnv(mode, process.cwd(), '')
  const viewportWidth = Number(env.VITE_ROOT_DIR)
  return {
    base: env.VITE_BASE_URL,
    define: {
      __GIT_BRANCH__: JSON.stringify(getGitBranch()),
      __BUILD_TIME__: Date.now(),
      __ENV__: Object.entries(env).reduce<Record<string, string>>((prev, [key, value]) => {
        if (key.startsWith('VITE_')) {
          prev[key] = value
        }
        return prev
      }, {}),
    },
    plugins: [
      vueattrPxtoremvw({
        viewportWidth,
        convertMode: 'vw',
        exclude: [/[\/\\]node_modules[\/\\]/],
      }),
      vue(),
      vueJsx(),
      AutoImport({
        resolvers: [VantResolver(), ElementPlusResolver()],
        dirs: ['src/autoImport/utils', 'src/autoImport/enum'],
        imports: ['vue', 'vue-router'],
      }),
      Components({
        resolvers: [
          VantResolver(),
          ElementPlusResolver(),
          {
            // 自动按需导入指令
            type: 'directive',
            resolve: (name) => ({
              name: 'default',
              from: `src/autoImport/directive/v${name}.ts`,
            }),
          },
        ],
        dirs: ['src/autoImport/components'],
      }),
      vueDevTools(),
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    css: {
      postcss: {
        plugins: [
          postcssPx2vp({
            viewportWidth(rule) {
              const file = rule.source?.input.file
              if (file) {
                if (/[\/\\]node_modules[\/\\]vant[\/\\]/.test(file)) {
                  return 375
                } else if (/[\/\\]node_modules[\/\\]element-plus[\/\\]/.test(file)) {
                  return 375
                }
              }
              return viewportWidth
            },
          }),
        ],
      },
    },
    server: {
      open: true,
      proxy: {
        [`^${env.VITE_PROXY_BASE_API}`]: {
          target: env.VITE_BASE_API,
          changeOrigin: true,
          rewrite: (path) =>
            path.replace(new RegExp(`^${env.VITE_PROXY_BASE_API.replaceAll('/', '\\/')}`), ''),
        },
      },
    },
    esbuild: {
      // 本地开发环境 或者 VITE_NO_CONSOLE=false 时不移除 console
      drop:
        env.NODE_ENV === 'development' || env.VITE_NO_CONSOLE === 'false'
          ? []
          : ['console', 'debugger'],
    },
  }
})
